<template>
  <div class="container">
    <div>
      <div class="menu-navbar">
        <el-button size="small" type="" @click="cancelSubmit">取消</el-button>
        <el-button size="small" type="success" @click="createSubmit('dataForm')">上传</el-button>
      </div>
      <div>
        <el-form ref="dataForm" :model="record" :rules="recordRules" label-position="top" size="small"  label-width="110px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                ref="upload"
                name="uploadDoc"
                list-type="picture"
                :action="fileUploadUrl"
                :auto-upload="false"
                :file-list="fileList"
                :limit="fileLimit"
                :headers="fileHeaders"
                :on-exceed="handleExceed"
                :before-upload="handleBeforeUpload"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :data="record"
                >
                <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip" style="text-align: left">只能上传{{fileType}}文件，且不超过{{fileSize}}MB</div>
              </el-upload>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="文档标题" prop="title">
                <el-input v-model="record.title" placeholder="文档标题"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="文档分类" prop="libraryCategoryName">
                <el-input v-model="record.libraryCategoryName" placeholder="文档分类" readonly="true" @click.native="toSelectCategory"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="文档标签" prop="keyword">
                <el-input v-model="record.keyword" placeholder="文档标签"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="文档简介" prop="description">
                <el-input type="textarea"  v-model="record.description" placeholder="文档简介"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog title="文档分类选择" :visible.sync="dialogSelectCategory" top="60px" custom-class="myDialog">
      <library-category-select @setLibraryCategory="setLibraryCategory"></library-category-select>
    </el-dialog>
  </div>
</template>
<script>
import { libraryCategorySelect } from '@/views/LibraryManage/LibraryDocInfo/components'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      fileUploadUrl: process.env.BASE_API + '/library' + '/LibraryDocInfo/upload',
      fileHeaders: {
        Authorization: 'bearer ' + getToken()
        // 'Content-Type': 'multipart/form-data'
      },
      fileList: [],
      fileLimit: 1,
      fileType: ['txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'],
      fileSize: 200, // 允许上传文件大小 单位 MB
      record: {
        libraryCategoryId: '',
        libraryCategoryName: '',
        title: '',
        keyword: '',
        description: ''
      },
      recordRules: {
        libraryCategoryName: [
          { message: '文档分类不能为空', required: true, trigger: 'blur' }
        ],
        title: [
          { message: '文档标题不能为空', required: true, trigger: 'blur' },
          { min: 1, max: 128, message: '最大长度为 128 个字符', trigger: 'blur' }
        ],
        keyword: [
          { min: 0, max: 256, message: '最大长度为 256 个字符', trigger: 'blur' }
        ],
        description: [
          { min: 0, max: 1024, message: '最大长度为 1024 个字符', trigger: 'blur' }
        ]
      },
      dialogSelectCategory: false
    }
  },
  created() {
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    // '$route.name': ['GetCodeList', 'GetCodeList1']
  },
  components: {
    libraryCategorySelect
  },
  methods: {
    submitUpload() {
      if (this.fileList == null || this.fileList.length <= 0) {
        this.$message({
          type: 'error',
          message: '请选择上传的文档!'
        })
        return false
      }

      for (let i = 0; i < this.fileList.length; i++) {
        let tempFile = this.fileList[i]
        let size = tempFile.size
        if (size > this.fileSize * 1024 * 1024) {
          this.$message({
            type: 'error',
            message: '上传文档太大!'
          })
          return false
        }

        let tempName = tempFile.name
        let type = tempName.substring(tempName.lastIndexOf('.') + 1)
        if (type) {
          type = type.toLocaleLowerCase()
        }
        let bool = this.fileType.includes(type)
        if (!bool) {
          this.$message({
            type: 'error',
            message: '上传文档类型错误!'
          })
          return false
        }
      }
      this.$refs.upload.submit()
    },
    handleChange(file, fileList) {
      console.log(fileList)
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleExceed(files, fileList) {
      this.fileList = []
      let tempLimit = this.fileLimit
      tempLimit = tempLimit > files.length ? files.length : tempLimit
      for (let i = 0; i < tempLimit; i++) {
        let tempFile = files[i]
        tempFile.status = 'ready'
        this.fileList.push(tempFile)
      }
    },
    handleBeforeUpload(file) {
    },
    handleSuccess(response) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
      } else {
        this.$message({
          type: 'error',
          message: response.message
        })
      }

      this.$router.push({
        name: 'libraryDocMyDoc',
        params: {}
      })
    },
    handleError(file, fileList) {
      this.fileList = []
      this.$message({
        type: 'error',
        message: '上传失败!'
      })
    },
    createSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitUpload()
        } else {
          this.$message({
            type: 'error',
            message: '上传失败!'
          })
          return false
        }
      })
    },
    cancelSubmit() {
      this.$router.push({
        name: 'libraryDocMyDoc'
      })
    },
    toSelectCategory() {
      //
      this.dialogSelectCategory = true
    },
    setLibraryCategory(args) {
      this.dialogSelectCategory = false
      if (args) {
        this.record.libraryCategoryId = args.id
        this.record.libraryCategoryName = args.name
      }
    }
  }
}
</script>
<style scoped>
  .menu-navbar{
    padding:0 0 20px;
    text-align: right;
  }
  .container{
    padding: 20px;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
